<html lang="zh-cn">
<head>
    <meta charset="utf-8"/>
    <title><%= title %></title>
    <link rel="icon" href="favicon.ico"/>
    <link rel="stylesheet" href="css/main.css"/>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
    var socket = io();
    var bUpdatingTips = false;
    let lineBuffer = '';
    let bScroll = true;

    function $$(id) {
        return document.getElementById(id);
    }

    function hideTips() {
        $('#tipsTable')[0] && ($('#tipsTable')[0].style.display = 'none');
    }

    function submitForm(formId, submitButtonId) {
        var repo = $('#repo').val();
        const customRepo = $('#customrepo').val();
        if (repo == 'custom' && customRepo == '') {
            alert('请输入仓库的url地址！');
            return;
        }
        hideTips();
        var formEle = $('#' + formId);
        var btnEle = $$(submitButtonId);
        btnEle.disabled = 'disabled';
        btnEle.value = '正在提取，请稍等！';
        var btnEle = $('#' + submitButtonId);
        btnEle.disabled = 'disabled';
        btnEle.value = '正在提取，请稍等！';
        $('#msgcontainer').empty();
        $('#messages')[0].style.display = 'block';
        // formEle.submit();
        var d = {
            action: formEle.attr('action')
        };
        var t = formEle.serializeArray();
        $.each(t, function () {
            if (this.name in d) {
                d[this.name] = d[this.name] + ',' + this.value;
            } else {
                d[this.name] = this.value;
            }
            // 特殊处理：自定义仓库URL
            if (this.name == 'repo' && this.value == 'custom') {
                d['repo'] = customRepo;
            }
        });
        socket.emit('add request', JSON.stringify(d));
    }

    socket.on('chat message', function (msg) {
        // appendMessage('[INFO]' + msg);
        appendMessage(msg);
    });

    socket.on('error message', function (msg) {
        appendMessage('[ERROR]' + msg);
    });

    function appendMessage(msg) {
        //console.log(msg);
        const changeLine = (msg[msg.length-1]=='\n');
        msg = msg.replace(/\r\n/g, '\n');
        var lines = msg.split('\n');
        if (lineBuffer.length > 0) {
            lines[0] = lineBuffer + lines[0];
            lineBuffer = '';
        }
        if (!changeLine) {
            lineBuffer = lines[lines.length-1];
            lines.splice(lines.length-1, 1);
        }
        lines.forEach(line => {
            if (line.indexOf('\r') >= 0) {
                var tmpblocks = line.split('\r');
                line = tmpblocks[tmpblocks.length-1];
            }
            if (line.substring(0, 8) == '[FINISH]') {
                let taskId = line.substring(8);
                const pos1 = taskId.indexOf('[');
                const pos2 = taskId.indexOf(']');
                taskId = taskId.substring(pos1 + 1, pos2);
                $('#msgcontainer').append('<a href="/download?id=' + taskId + '">下载结果文件（一小时内有效）</a>');
                $('#msgcontainer').append($('<div>').addClass('finishMsg').html('成功完成'));
                $$('submitSingle').disabled = '';
                $$('submitSingle').value = '开始提取';
            } else if (line.substring(0, 7) == '[ERROR]') {
                $('#msgcontainer').append($('<div>').addClass('errMsg').html(line));
                $$('submitSingle').disabled = '';
                $$('submitSingle').value = '开始提取';
            } else {
                $('#msgcontainer').append($('<div>').html(line));
            }
            if ($('#msgcontainer')[0].children.length > 2000) {
                $('#msgcontainer')[0].removeChild($('#msgcontainer')[0].children[0]);
            }
        });
        if (bScroll) {
            document.getElementById('msg_end').scrollIntoView();
        }
        // $('msg_end').focus();
    }

    function showMessages() {
        $('#messages')[0].style.display = 'block';
    }

    function clearMessages() {
        $('#messages')[0].style.display = 'none';
    }

    function searchKeyword() {
        var pkgnameEle = $$('pkgname');
        var pkgname = pkgnameEle.value;
        if (pkgname == '') {
            pkgname = 'hello';
        }
        var url = 'https://pypi.tuna.tsinghua.edu.cn/simple/' + pkgname;
        window.open(url);
    }

    function listPackage() {
        if (bUpdatingTips) {
            return;
        }
        var repo = $('#repo').val();
        const customRepo = $('#customrepo').val();
        if (repo == 'custom') {
            if (customRepo == '') {
                alert('请输入仓库的url地址！');
                return;
            }
            repo = customRepo;
        }
        $$('listBtn').disabled = 'disabled';
        var pkgnameEle = $('#pkgname');
        var pkgname = pkgnameEle.val();
        if (pkgname.length == 0) {
            alert('请输入要列出的包名');
            return;
        }
        var timeStamp = Date.now();
        var url = '/search/package/' + pkgname + '?tm=' + timeStamp;
        $.ajax({
            url: url,
            dataType: 'json',
            data: {
                repo: repo
            },
            success: function(data) {
                if ($('#tipsTable').length > 0) {
                    $('#tipsTable').remove();
                }
                if (data.length > 0) {
                    var tbodyEle = $('<tbody>').append($('<tr>')
                        .append($('<th>').text('包名'))
                        .append($('<th>').html('包版本<br><select id="versionSelect" onchange="renderTips()"></select>'))
                        .append($('<th>').html('python版本<br><select id="pyverSelect" onchange="renderTips()"></select>'))
                        .append($('<th>').html('abi版本<br><select id="abiverSelect" onchange="renderTips()"></select>'))
                        .append($('<th>').html('os信息<br><select id="osverSelect" onchange="renderTips()"></select>'))
                        .append($('<th>').html('类型'))
                        .append($('<th>').html('<a href="javascript:void(0)" title="关闭提示" onclick="hideTips()">[X]</a><br>操作')));
                    var tableEle = $('<table id="tipsTable">').addClass('tipsTable').append(tbodyEle);
                    var versions = {};
                    var pyvers = {};
                    var abivers = {};
                    var osvers = {};
                    data.forEach(one => {
                        var pyver = [];
                        if (one.pyver != '（全部）') {
                            pyver = one.pyver.split('.');
                        }
                        var trEle = $('<tr>');
                        trEle.append($('<td>').text(one.pkgname));
                        trEle.append($('<td>').text(one.version));
                        trEle.append($('<td>').text(one.pyver));
                        trEle.append($('<td>').text(one.abiver));
                        trEle.append($('<td>').text(one.osvers.join(',')));
                        trEle.append($('<td>').text(one.filetype));
                        trEle.append($('<td>').html('<a class="smlLnk" href="javascript:void(0)"' + 
                            ' onclick="writePackage(\'' + one.pkgname + '\',\'' + 
                            one.version + '\',\'' + pyver.join(',') + '\',\'' + one.abiver + '\',\'' + 
                            one.osvers.join(',') + '\')">选中</a>'));
                        tbodyEle.append(trEle);
                        if (!versions[one.version]) {
                            versions[one.version] = 1;
                        } else {
                            versions[one.version]++;
                        }
                        pyver.forEach(oneVer => {
                            if (oneVer != '') {
                                if (!pyvers[oneVer]) {
                                    pyvers[oneVer] = 1;
                                } else {
                                    pyvers[oneVer]++;
                                }
                            }
                        });
                        if (one.abiver != '') {
                            if (!abivers[one.abiver]) {
                                abivers[one.abiver] = 1;
                            } else {
                                abivers[one.abiver]++;
                            }
                        }
                        one.osvers.forEach(osver => {
                            if (osver != '') {
                                if (!osvers[osver]) {
                                    osvers[osver] = 1;
                                } else {
                                    osvers[osver]++;
                                }
                            }
                        });
                    });
                    // 设置table的位置，然后显示出来
                    tableEle.css('left', pkgnameEle[0].getBoundingClientRect().left - 320);
                    tableEle.css('top', pkgnameEle[0].getBoundingClientRect().bottom + 2);
                    $('body').append(tableEle);
                    // 列头增加▼下拉筛选
                    $('#versionSelect').append ("<option value=''>==请选择==</option>");
                    for (var one in versions) {
                        $('#versionSelect').append ("<option value='"+one+"'>"+one+"</option>");
                    }
                    $('#pyverSelect').append ("<option value=''>==请选择==</option>");
                    for (var one in pyvers) {
                        $('#pyverSelect').append ("<option value='"+one+"'>"+one+"</option>");
                    }
                    $('#abiverSelect').append ("<option value=''>==请选择==</option>");
                    for (var one in abivers) {
                        $('#abiverSelect').append ("<option value='"+one+"'>"+one+"</option>");
                    }
                    $('#osverSelect').append ("<option value=''>==请选择==</option>");
                    for (var one in osvers) {
                        $('#osverSelect').append ("<option value='"+one+"'>"+one+"</option>");
                    }
                } else {
                    alert('未找到符合的whl包！');
                }
                $$('listBtn').disabled = '';
            }
        });
    }

    function renderTips() {
        var version = $('#versionSelect').val();
        var pyver = $('#pyverSelect').val();
        var abiver = $('#abiverSelect').val();
        var osver = $('#osverSelect').val();
        var trEles = $('#tipsTable tr');
        for (var i  = 1; i < trEles.length; i++) {
            var bMatch = true;
            if (version.length > 0 && trEles[i].children[1].innerText != version) {
                bMatch = false;
            }
            if (pyver.length > 0 && trEles[i].children[2].innerText != pyver) {
                bMatch = false;
            }
            if (abiver.length > 0 && trEles[i].children[3].innerText != abiver) {
                bMatch = false;
            }
            if (osver.length > 0 && trEles[i].children[4].innerText != osver) {
                bMatch = false;
            }
            if (bMatch) {
                trEles[i].style.display = '';
            } else {
                trEles[i].style.display = 'none';
            }
        }
    }

    function writePackage(pkgname, version, pyversStr, abiver, osversStr) {
        bUpdatingTips = true;
        var pyvers = pyversStr.split(',');
        var pyver = '';
        if (pyvers.length > 0) {
            pyver = pyvers[pyvers.length-1];
        }
        var osvers = osversStr.split(',');
        var osver = '';
        if (osvers.length > 0) {
            osver = osvers[osvers.length-1];
        }
        $('#pkgname').val(pkgname);
        $('#version').val(version);
        $('#pyver').val(pyver);
        $('#abiver').val(abiver);
        $('#osver').val(osver);
        $('#tipsTable').remove();
        bUpdatingTips = false;
    }

    function searchPackage() {
        var pkgnameEle = $$('pkgname');
        var pkgname = pkgnameEle.value;
        if (pkgname == '') {
            pkgname = 'hello';
        }
        var url = 'https://pypi.org/search/?q=' + pkgname;
        window.open(url);
    }

    function autoChangePackName() {
        var pkgnameEle = $$('pkgname');
        var pkgname = pkgnameEle.value;
        var verEle = $$('version');
        var version = verEle.value;
        var pyverEle = $$('pyver');
        var abiverEle = $$('abiver');
        var osverEle = $$('osver');

        var pos = pkgname.indexOf('==');
        if (pos > 0) {
            if (version == '') {
                pkgnameEle.value = pkgname.substring(0, pos);
                verEle.value = pkgname.substring(pos + 2);
            }
        } else if (pkgname.indexOf('.whl') == pkgname.length - 4) {
            // pandas-1.5.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
            const fnBlocks = pkgname.split('-');
            if (fnBlocks.length == 5) {
                const osInfo = fnBlocks[4];
                const pos = osInfo.indexOf('.');
                if (pos > 0) {
                    osInfo = osInfo.substring(0, pos);
                }
                pkgnameEle.value = fnBlocks[0];
                verEle.value = fnBlocks[1];
                pyverEle.value = fnBlocks[2];
                abiverEle.value = fnBlocks[3];
                osverEle.value = osInfo;
            }
        }
    }

    function changeRepo() {
        let repo = $('#repo').val();
        if (repo == 'custom') {
            $('#customrepo')[0].style.display = '';
        } else {
            $('#customrepo')[0].style.display = 'none';
        }
    }

    window.onload = function () {
        var timeStamp = Date.now();
        var url = '/env/pip' + '?tm=' + timeStamp;
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(data) {
                if (data.length > 0) {
                    $('#pipSelect option').remove();
                    data.forEach(one => {
                        $('#pipSelect').append ("<option value='" + one.fullPath + "'>" + one.versionStr + "</option>");
                    });
                } else {
                    alert('未找到pip程序！');
                }
                $$('listBtn').disabled = '';
            }
        });
    }
    </script>
</head>
<body>
    <center>
    <h1>欢迎使用 <%= title %></h1>
    <br/>
    <div>
        <form id='editsingle' method='post' action='/uploadsingle'>
            <table><tbody>
                <tr>
                    <td style="width:120px;">仓库源：</td>
                    <td style="width:400px;">
                        <select id="repo" name="repo" onchange="changeRepo()">
                            <option value="https://pypi.tuna.tsinghua.edu.cn/simple/">清华源</option>
                            <option value="https://mirrors.aliyun.com/pypi/simple/">阿里源</option>
                            <option value="http://repo.huaweicloud.com/repository/pypi/simple/">华为源</option>
                            <option value="http://pypi.douban.com/simple/">豆瓣源</option>
                            <option value="https://mirrors.bfsu.edu.cn/pypi/web/simple/">北外源</option>
                            <option value="https://pypi.python.org/simple/">官方源</option>
                            <option value="custom">自定义</option>
                        </select>
                        <input type="text" id="customrepo" style="display: none;" />
                    </td>
                </tr>
                <tr>
                    <td>pip版本：</td>
                    <td>
                        <select id="pipSelect" name="pip">
                            <option value="">==加载中==</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>包名：</td>
                    <td>
                        <input name="pkgname" id='pkgname' type='text' onchange="autoChangePackName()" />
                        &nbsp;&nbsp;
                        <input id="listBtn" type="button" value='列出版本' onclick="listPackage()" />
                        &nbsp;&nbsp;
                        <input type="button" value='从pypi.org搜索' onclick="searchPackage()" />
                    </td>
                </tr>
                <tr>
                    <td>包版本：</td><td><input name="version" id='version' type='text' /></td>
                </tr>
                <tr>
                    <td>python版本：</td><td><input name="pyver" id='pyver' type='text' /></td>
                </tr>
                <tr>
                    <td>abi版本：</td><td><input name="abiver" id='abiver' type='text' /></td>
                </tr>
                <tr>
                    <td>操作系统：</td><td><input name="osver" id='osver' type='text' /></td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center">
                    <input type='button' id='submitSingle' value='开始提取' onclick="submitForm('editsingle','submitSingle')" />
                </td></tr>
            </tbody></table>
        </form>
    </div>
    <div>
        <a href="/cmd" target="_blank">执行命令</a>
    </div>
    </center>
    <div id='messages'>
        <div class='closebtn'><input type='checkbox' id='autoScroll' checked='checked' onchange='bScroll=this.checked'/><label for='autoScroll'>自动滚屏</label>&nbsp;&nbsp;<a href="javascript:void(0)" onclick="clearMessages()">[关闭]</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>
        <div id='msgcontainer'></div>
        <div id='msg_end'></div>
    </div>
    <div id='operatebar'><a href="javascript:void(0)" onclick="showMessages()">[显示提取进度]</a></div>
</body>
</html>
